import 'package:flutter_chat/common/api/apis.dart';
import 'package:flutter_chat/common/constant/constants.dart';
import 'package:flutter_chat/common/entity/entitys.dart';
import 'package:flutter_chat/common/service/services.dart';
import 'package:flutter_chat/common/utils/utils.dart';
import 'package:flutter_chat/common/widget/widgets.dart';
import 'package:get/get.dart';

class UserStore extends CustomGetxController {
  static UserStore get to => Get.find();
  final StorageService storageService = StorageService.to;

  /// 登录状态
  final _isLogin = false.obs;
  set isLogin(bool value) => _isLogin.value = value;
  bool get isLogin => _isLogin.value;

  /// 用户Token
  final _token = "".obs;
  set token(String value) => _token.value = value;
  String get token => _token.value;

  /// 用户信息
  final _user = User().obs;
  set user(User value) => _user.value = value;
  User get user => _user.value;

  /// 初始化
  @override
  void onInit() async {
    super.onInit();
    // 读取Token
    getToken();
    // 判断Token是否存在
    if (!StringUtil.isEmpty(token)) {
      // 设置登录状态
      isLogin = true;
      // 读取用户信息
      getUserInfoLocal();
    }
  }

  /// 用户登录
  Future<bool> login({
    required String username,
    required String password,
  }) async {
    if (StringUtil.isEmpty(username) || StringUtil.isEmpty(password)) {
      ToastUtil.errorNotification(subTitle: "用户名或密码不能为空");
      return false;
    }
    ResponseEntity response = await UserApi.login(username, password);
    if (response.code == 0) {
      // 获取Token
      setToken(response.data["token"]);
      // 设置登录状态
      isLogin = true;
      // 获取用户信息
      await getUserInfo();
      // 登录成功
      ToastUtil.text("登录成功");
      return true;
    }
    ToastUtil.errorNotification(subTitle: response.msg);
    return false;
  }

  /// 获取用户信息
  Future<void> getUserInfo() async {
    ResponseEntity response = await UserApi.getLoginUser();
    if (response.code == 0) {
      // 获取用户信息
      user = User.fromJson(response.data);
      // 保存用户信息
      setUserInfo();
    }
  }

  /// 退出登录
  void logout() {
    // 清空Token
    setToken("");
    // 设置登录状态
    isLogin = false;
    // 清空用户信息
    user = User();
    // 清空用户信息
    storageService.remove(StorageName.userInfo);
    // 当前页面不是登录页时
    if (Get.currentRoute != RouterName.login) {
      // 跳转到登录页
      Get.offAllNamed(RouterName.login);
    }
  }

  /// 设置Token
  void setToken(t) {
    token = t;
    storageService.setString(StorageName.token, t);
  }

  /// 读取Token
  void getToken() {
    token = storageService.getString(StorageName.token);
  }

  /// 保存用户信息
  void setUserInfo() {
    storageService.setMap(StorageName.userInfo, user.toJson());
  }

  /// 读取用户信息
  void getUserInfoLocal() {
    user = User.fromJson(storageService.getMap(StorageName.userInfo));
  }
}
